/* eslint-disable */
'use strict'
const express = require('express')
const router = express.Router()
const node_xlsx = require('node-xlsx')
const fs = require('fs')
const dbconnection = require('../config/database.js')
const path = require('path')

const queryInfos = (mobile, callback) => {
  dbconnection.execute('SELECT * FROM infos', callback)
}
const setupData = (res, datas) => {
  let myDatas = [['编号','姓名','手机','生日','左','右']];
  datas.forEach((data, index) => {
    let datas = [];
    for (let item in data) {
      datas.push(data[item])
    }
    myDatas.push(datas)
  })
  writeXls(res, myDatas)  
}
const writeXls = (res, datas) => {
  var buffer = node_xlsx.build([
    {"name": "Info", "data": datas}
  ]);
  // fs.writeFileSync("Group.csv", buffer, 'binary');//生成excel文件
  res.setHeader('Content-disposition', 'attachment; filename=' + 'Info.xlsx');
  res.setHeader('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  res.write(buffer);
  res.end();
  // let downloadPath = path.resolve(__dirname, '../Group.csv');
  // var filestream = fs.createReadStream(downloadPath);
  // filestream.on('data', (chunk) => {
  //     res.write(chunk);
  // });
  // filestream.on('end', () => {
  //     res.end();
  // });
}
/* POST execl listing. */
router.get('/excel', (req, res, next) => {
  queryInfos(req.body.mobile, (err, results, fields) => {
    if (err) {
      throw err;
    }
    if (results.length > 0) {
      setupData(res, results)
    }
  });
});

module.exports = router;
